package com.bida.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bida.context.BaseContext;
import com.bida.domain.dto.CategoryDTO;
import com.bida.domain.po.Category;
import com.bida.domain.po.Dish;
import com.bida.domain.po.Setmeal;
import com.bida.exception.BaseException;
import com.bida.mapper.CategoryMapper;
import com.bida.result.PageResult;
import com.bida.result.Result;
import com.bida.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bida.service.IDishService;
import com.bida.service.ISetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.bida.constant.MessageConstant.*;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-09-06
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Resource
    private IDishService dishService;

    @Resource
    private ISetmealService setmealService;

    /**
     * 分页查询分类
     * @param name
     * @param page
     * @param pageSize
     * @param type
     * @return
     */
    @Override
    public Result<PageResult> pageGetCategory(String name, Integer page, Integer pageSize, Integer type) {
        IPage<Category> nowPage = new Page<>(page, pageSize);
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        if (name != null){
            categoryQueryWrapper.like("name",name);
        }
        if (type != null){
            categoryQueryWrapper.eq("type",type);
        }
        categoryQueryWrapper.orderByAsc("sort");
        IPage<Category> categoryIPage = this.page(nowPage, categoryQueryWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(categoryIPage.getTotal());
        pageResult.setRecords(categoryIPage.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 新增菜品
     * @param categoryDTO
     * @return
     */
    @Override
    public Result insertNewCategory(CategoryDTO categoryDTO) {
        // 1.判断 id 是否已经存在
        Long id = categoryDTO.getId();
         if (id != null){
             Category category = this.getById(id);
             if (category != null){
                 throw new BaseException(CATEGORY_ID_EXIST);
             }
         }
         // 2.判断套餐名称是否已经存在
        Category one = this.lambdaQuery()
                .eq(Category::getName, categoryDTO.getName())
                .one();
         if (one != null){
             throw new BaseException(CATEGORY_NAME_EXIST);
         }
         // 3.保存
        Category category = new Category();
         BeanUtils.copyProperties(categoryDTO, category);
         category.setCreateTime(LocalDateTime.now());
         category.setUpdateTime(LocalDateTime.now());
         // 获取当前登录用户id
         Long userId = BaseContext.getCurrentId();
        System.out.println("userId = " + userId);
         category.setCreateUser(userId);
         category.setUpdateUser(userId);
         this.save(category);
        return Result.success();
    }

    /**
     * 启用、禁用分类
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result updateStatusById(Integer status, Long id) {
        // 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        category.setUpdateUser(userId);
        category.setUpdateTime(LocalDateTime.now());
        this.updateById(category);
        return Result.success();
    }

    /**
     * 修改分类
     * @param categoryDTO
     * @return
     */
    @Override
    public Result updateCategoryInfoById(CategoryDTO categoryDTO) {
        // 查询当前登录人id
         Long userId = BaseContext.getCurrentId();
         // 感觉不用查了吧感觉,反正分页回显了，肯定是存在的了
         Category category = new Category();
         BeanUtils.copyProperties(categoryDTO, category);
         category.setUpdateTime(LocalDateTime.now());
         category.setUpdateUser(userId);
         boolean b = this.updateById(category);
         if (!b){
            return Result.error(CATEGORY_UPDATE_FAIL);
         }
         return Result.success();
    }

    /**
     * 根据 id 删除分类
     * @param id
     * @return
     */
    @Override
    public Result deleteCategoryById(Long id) {
        if (id == null){
            return Result.error(CAN_NOT_USE_NULL_ID);
        }
        // 判断当前分类是否关联菜品
        List<Dish> dishList = dishService.lambdaQuery()
                .eq(Dish::getCategoryId, id)
                .list();
        if (!dishList.isEmpty()){
            throw new BaseException(CATEGORY_BE_RELATED_BY_DISH);
        }
        // 判断当前分类是否关联了套餐
        List<Setmeal> setmealList = setmealService.lambdaQuery().eq(Setmeal::getCategoryId, id).list();
        if (!setmealList.isEmpty()){
            throw new BaseException(CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        // 删除
        this.removeById(id);
        return Result.success();
    }

    /**
     * 根据类型查询分类 分页
     * @param type
     * @return
     */
    @Override
    public Result<List<Category>> getPageCategoryList(Integer type) {
        List records = this.pageGetCategory(null, 1, 500, type).getData().getRecords();
        return Result.success(records);
    }

    /**
     * 根据类型查询分类
     * @param type
     * @return
     */
    @Override
    public List<Category> getAllList(Integer type) {
        return categoryMapper.getAllList(type);
    }
}
